package src

import (
    "log"

    util "github.com/alibabacloud-go/tea-utils/v2/service"
    "github.com/alibabacloud-go/tea/tea"
)

type Handler struct {
}

func NewHandler() *Handler {
    return &Handler{}
}

func (h Handler) DoRenew() {
    util2 := NewUtil()
    accessKeyId := util2.GetEnv("accessKeyId", "ak")
    if accessKeyId == "" {
        log.Fatalln("ak(accessKeyId) can not be nil")
    }
    accessKeySecret := util2.GetEnv("accessKeySecret", "sk")
    if accessKeySecret == "" {
        log.Fatalln("sk(accessKeySecret) can not be nil")
    }
    domainName := util2.GetEnv("domainName", "dn")
    if domainName == "" {
        log.Fatalln("dn(domainName) can not be nil")
    }

    rr, domain := util2.SplitDomainName(domainName)

    // 初始化AliyunService
    service := NewAliyunService(accessKeyId, accessKeySecret)
    resp, err := service.DescribeDomainRecords(domain, rr, "A")
    if tea.BoolValue(util.IsUnset(tea.ToMap(resp))) {
        log.Println(tea.String("错误参数！"))
        return
    }

    outsideIp, err := util2.GetOutsideIpStr()
    if err != nil {
        log.Printf("获取外网ip失败: %v", err)
        return
    }

    if len(resp.Body.DomainRecords.Record) == 0 {
        log.Printf("未找到解析记录, 创建新的解析记录 (%s)", domainName)
        rr, domain := util2.SplitDomainName(domainName)

        // 创建一个新的解析记录
        err := service.CreateRecord(outsideIp, rr, domain)
        if err != nil {
            log.Printf("解析 rr: %s, domain: %s 失败: %v", rr, domain, err)
            return
        }
        return
    } else {
        record := resp.Body.DomainRecords.Record[0]
        if outsideIp != "" && *record.Value != outsideIp {
            // 重新解析
            log.Printf("重新解析 (%s)->(%s)", *record.Value, outsideIp)
            _ = service.UpdateDomainRecord(*record.RecordId, outsideIp, *record.RR, "A")
        }
    }
}
